package org.itsky.study.test3;

import org.itsky.study.test2.Employee;
import org.itsky.study.test2.EmployeeData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * @Author sky
 * @Site cmtianxie163.com 2020/4/13 11:52
 */
public class StreamAPITest2 {
    public static void main(String[] args) {
        /**
         * 1. 筛选与切片
         */
        List<Employee> list = EmployeeData.getEmployees();
        //练习：查询员工表中薪资大于7000的员工信息
        list.stream().filter(employee -> employee.getSalary()>7000).forEach(System.out::println);
        System.out.println("-------------------");
        //截断流，使其元素不超过给定数量
        list.stream().limit(3).forEach(System.out::println);
        System.out.println("-------------------");
        //跳过元素，返回一个扔掉了前 n 个元素的流
        list.stream().skip(3).forEach(System.out::println);
        System.out.println("-------------------");
        //筛选，通过流所生成元素的 hashCode() 和 equals() 去除重复元素
        list.stream().distinct().forEach(System.out::println);

        /**
         * 2. 映射
         */

        List<String> list1 = Arrays.asList("aa", "bb", "cc", "dd", "ee");
        list1.stream().skip(1).map(str -> str.toUpperCase()).forEach(System.out::println);
        System.out.println("-------------------");
        //获取员工姓名长度大于3的员工的姓名
        list.stream().map(Employee::getName).filter(name -> name.length()>3).forEach(System.out::println);

        Stream<Stream<Character>> streamStream = list1.stream().map(StreamAPITest2::fromStringToStream);
        streamStream.forEach(System.out::println);
        System.out.println("-------------------");
        //flatMap
        Stream<Character> characterStream = list1.stream().flatMap(StreamAPITest2::fromStringToStream);
        characterStream.forEach(System.out::println);
        System.out.println("-------------------");

        /**
         * 3. 排序
         */
        //自然排序
        List<Integer> list2 = Arrays.asList(1,4,7,3,2,8,111,4);
        list2.stream().sorted().forEach(System.out::println);
        //定制排序
        //安装年龄排序 年龄相同的再安装薪资排序
        list.stream().sorted(((o1, o2) -> {
            int compare = Integer.compare(o1.getAge(), o2.getAge());
            if(compare == 0){
                return Double.compare(o1.getSalary(),o2.getSalary());
            }else{
                return compare;
            }
        })).forEach(System.out::println);
    }

    //将字符串中的多个字符构成的集合转换为对应的Stream实例
    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character> list = new ArrayList<>();
        for (Character c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }
}
